package com.lkd.job;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.common.VMSystem;
import com.lkd.entity.UserEntity;
import com.lkd.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class UserJob {

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @XxlJob("userTaskCountInit")
    public ReturnT<String> initUserTaskCount(String param) {
        log.info("接收到xxl-job的调度任务，任务参数：{}", param);

        long time = DateUtil.offset(new Date(), DateField.DAY_OF_MONTH, Integer.parseInt(param)).getTime();
        String format = new SimpleDateFormat("yyyyMMdd").format(new Date(time));

        LambdaQueryWrapper<UserEntity> wrapper = Wrappers.<UserEntity>lambdaQuery()
                .in(UserEntity::getRoleCode, "1002", "1003")
                .eq(UserEntity::getStatus, 1);
        List<UserEntity> userEntityList = userService.list(wrapper);


        userEntityList.stream().forEach(userEntity -> {
            String key = VMSystem.REGION_TASK_KEY_PREF + format + "." + userEntity.getRegionId() + "." + userEntity.getRoleCode();
            stringRedisTemplate.opsForZSet().add(key, userEntity.getId() + "", 0);
        });


        return ReturnT.SUCCESS;
    }
}
